import {getCurrentUser} from "../api/login/index";
import {getUserInfo} from "../api/organizational/user";
import {setUser} from "./userUtils";
import storage from "./storageUtils";

function hasAuthority(authorityObjs, route) {
  if (route.meta && route.meta.authorities) {
    return authorityObjs.some(authorityObj => route.meta.authorities.includes(authorityObj))
  } else {
    return true
  }
}

export function filterAsyncRoutes(routes, authorities) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasAuthority(authorities, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, authorities)
      }
      res.push(tmp)
    }
  })
  return res
}

export function deleteAuthorities() {
  storage.remove("authorityList");
}

export function setAuthorities(authorities) {
  deleteAuthorities();
  storage.setJson("authorityList", authorities);
}

export function getAuthorities() {
  const authorities = storage.getJson("authorityList");
  if (authorities) {
    return authorities.authorities
  }
  return null;
}

export function getUserAuthorities() {
  return new Promise((resolve, reject) => {
    getCurrentUser(res => {
      let authorities = res.authorities;
      // 保存权限信息
      setAuthorities(res);
      // 获取用户信息
      getUserInfo(res.username, user => {
        setUser(user);
        return resolve(authorities);
      }).catch(e => {
        reject(e)
      });
    }).catch(e => {
      reject(e)
    })
  });
}

export function checkAuthorities(value) {
  if (value && value instanceof Array && value.length > 0) {
    const authorities = getAuthorities();
    const authoritiesAttrs = value
    return authorities.some(authorityObj => {
      return authoritiesAttrs.includes(authorityObj)
    })
  } else {
    console.error("need authorities! Like ['admin']")
    return false
  }
}

export function getRoutes() {
  return storage.getJson("routes");
}

export function setRoutes(routes) {
  storage.remove("routes");
  storage.setJson("routes", routes);
}


